<?php
namespace app\admin\controller;
use app\admin\logic\RoleLogic;

/**
 * 角色权限api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2020/04/08
 * Time: 14:27
 */
class Role extends Base {

    public function __construct(){
        parent::__construct();
        $this->r_logic = new RoleLogic();
    }

    /**
     * 获取角色
     * @return \think\response\Json
     */
    public function ajax_get_role(){
        $params = input();
        $r = $this->check_admin_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        $maps = $this->r_logic->get_search_role_maps();
        $limit = ($params['page'] - 1) * $params['rows'];

        $list = model('role')->get_list($maps,'id,name','id asc','',$limit,$params['rows']);

        $total_num = model('role')->get_count($maps,'id');

        $data['list'] = $list;
        $data['total_num'] = $total_num;
        return json($this->r_logic->get_response(1,'OK',$data));
    }

    /**
     * 获取角色详情
     * @return \think\response\Json
     */
    public function ajax_get_role_detail(){
        $params = input();
        $r = $this->check_admin_token($params);
        if($r['code'] != 1){
            return json($r);
        }


        $maps = [];
        $maps[] = ['id','=',$params['roleid']];
        $detail = model('role')->get_detail($maps);
        $detail['mini_ws_detail'] = !empty($detail['mini_ws_detail']) ? json_decode($detail['mini_ws_detail'],true) : [];

        $data['detail'] = $detail;
        return json($this->r_logic->get_response(1,'OK',$data));
    }

    /**
     * 修改角色
     * @return \think\response\Json
     */
    public function ajax_save_role(){
        $params = input();
        $r = $this->check_admin_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        //检查修改角色规则
        $r = $this->r_logic->check_save_role_rule($params);
        if(!$r['code']){
            return json($r);
        }
        $r_detail = $r['data']['r_detail'];

        $r_data = [];
        $r_data['mini_ws_detail'] = json_encode($params['mini_ws_detail'],JSON_UNESCAPED_UNICODE);

        $maps = [];
        $maps[] = ['id','=',$r_detail['id']];
        $r = model('role')->force()->save($r_data,$maps);
        if($r !== false){
            return json($this->r_logic->get_response(1,'修改成功'));
        }
        return json($this->r_logic->get_response(0,'修改失败'));
    }
}